/**
 * 骰子指令解析器
 * 支持格式：
 * .r 1d100 - 基础掷骰
 * .r 2d6+1d4 - 复合掷骰
 * .r 1d100+50 - 带加值掷骰
 * .check 侦查 70 - 技能检定
 */

class DiceParser {
  constructor() {
    this.dicePattern = /^\.r\s+(\d+d\d+(?:\+\d+d\d+)*(?:\+\d+)?)$/;
    this.checkPattern = /^\.check\s+(\w+)\s+(\d+)$/;
  }

  /**
   * 解析骰子指令
   * @param {string} command - 骰子指令
   * @returns {Object} 解析结果
   */
  parseCommand(command) {
    const trimmedCommand = command.trim();
    
    // 检查是否是技能检定
    const checkMatch = trimmedCommand.match(this.checkPattern);
    if (checkMatch) {
      return this.parseCheckCommand(checkMatch);
    }
    
    // 检查是否是掷骰指令
    const diceMatch = trimmedCommand.match(this.dicePattern);
    if (diceMatch) {
      return this.parseDiceCommand(diceMatch[1]);
    }
    
    throw new Error('无效的骰子指令格式');
  }

  /**
   * 解析技能检定指令
   * @param {Array} match - 正则匹配结果
   * @returns {Object} 检定结果
   */
  parseCheckCommand(match) {
    const skillName = match[1];
    const skillValue = parseInt(match[2]);
    
    if (skillValue < 1 || skillValue > 100) {
      throw new Error('技能值必须在1-100之间');
    }
    
    const diceResult = this.rollDice(1, 100);
    const isSuccess = this.checkSuccess(diceResult, skillValue);
    
    return {
      type: 'check',
      skillName,
      skillValue,
      diceResult,
      isSuccess,
      successLevel: this.getSuccessLevel(diceResult, skillValue),
      command: `.check ${skillName} ${skillValue}`
    };
  }

  /**
   * 解析掷骰指令
   * @param {string} diceString - 骰子字符串
   * @returns {Object} 掷骰结果
   */
  parseDiceCommand(diceString) {
    const parts = diceString.split('+');
    const diceResults = [];
    let total = 0;
    
    for (const part of parts) {
      const trimmedPart = part.trim();
      
      if (trimmedPart.includes('d')) {
        // 骰子部分 (如 2d6)
        const diceResult = this.parseDicePart(trimmedPart);
        diceResults.push(diceResult);
        total += diceResult.total;
      } else {
        // 固定加值 (如 +5)
        const bonus = parseInt(trimmedPart);
        if (isNaN(bonus)) {
          throw new Error(`无效的加值: ${trimmedPart}`);
        }
        total += bonus;
        diceResults.push({
          type: 'bonus',
          value: bonus,
          display: `+${bonus}`
        });
      }
    }
    
    return {
      type: 'dice',
      diceResults,
      total,
      command: `.r ${diceString}`
    };
  }

  /**
   * 解析骰子部分
   * @param {string} dicePart - 骰子部分字符串
   * @returns {Object} 骰子结果
   */
  parseDicePart(dicePart) {
    const [count, sides] = dicePart.split('d').map(Number);
    
    if (isNaN(count) || isNaN(sides) || count < 1 || sides < 1) {
      throw new Error(`无效的骰子格式: ${dicePart}`);
    }
    
    if (count > 100) {
      throw new Error('单次掷骰数量不能超过100');
    }
    
    if (sides > 1000) {
      throw new Error('骰子面数不能超过1000');
    }
    
    const rolls = [];
    let total = 0;
    
    for (let i = 0; i < count; i++) {
      const roll = this.rollDice(1, sides);
      rolls.push(roll);
      total += roll;
    }
    
    return {
      type: 'dice',
      count,
      sides,
      rolls,
      total,
      display: `${count}d${sides}`
    };
  }

  /**
   * 掷骰子
   * @param {number} min - 最小值
   * @param {number} max - 最大值
   * @returns {number} 骰子结果
   */
  rollDice(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  /**
   * 检查技能检定是否成功
   * @param {number} diceResult - 骰子结果
   * @param {number} skillValue - 技能值
   * @returns {boolean} 是否成功
   */
  checkSuccess(diceResult, skillValue) {
    return diceResult <= skillValue;
  }

  /**
   * 获取成功等级
   * @param {number} diceResult - 骰子结果
   * @param {number} skillValue - 技能值
   * @returns {string} 成功等级
   */
  getSuccessLevel(diceResult, skillValue) {
    if (diceResult > skillValue) {
      return '失败';
    }
    
    if (diceResult <= Math.floor(skillValue / 5)) {
      return '极难成功';
    }
    
    if (diceResult <= Math.floor(skillValue / 2)) {
      return '困难成功';
    }
    
    return '普通成功';
  }

  /**
   * 格式化结果显示
   * @param {Object} result - 解析结果
   * @returns {string} 格式化字符串
   */
  formatResult(result) {
    if (result.type === 'check') {
      const { skillName, skillValue, diceResult, isSuccess, successLevel } = result;
      return `${skillName}检定: ${diceResult}/${skillValue} ${isSuccess ? successLevel : '失败'}`;
    }
    
    if (result.type === 'dice') {
      const { diceResults, total } = result;
      const parts = diceResults.map(dr => {
        if (dr.type === 'dice') {
          const rollsStr = dr.rolls.join(', ');
          return `${dr.display}(${rollsStr})`;
        } else {
          return dr.display;
        }
      });
      
      return `${parts.join(' + ')} = ${total}`;
    }
    
    return '未知结果';
  }
}

export default DiceParser;
